Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

115
Visualizações
JavaScript: How to better indicate (highlight) current nav page during scroll than just using "scrollY > x"

I currently have a simple webpage layout that is divided in 4 sections (HOME / ABOUT / SKILLS / CONTACT).

Here is my JS code that highlights a specific section from the Nav-bar when a certain pixel amount has been reached during scroll:

let home = document.querySelector(".btn1")
let about = document.querySelector(".btn2")
let skills = document.querySelector(".btn3")
let contact = document.querySelector(".btn4")

function highlight(){
  if(window.scrollY > 1)
  {
    home.classList.add("highlight")
  }

  if(window.scrollY > 550)
  {
    home.classList.remove("highlight")
    about.classList.add("highlight")
  }
  else{
    about.classList.remove("highlight")
  }

  if(window.scrollY > 1210)
  {
    skills.classList.add("highlight")
    about.classList.remove("highlight")
  }
  else{
    skills.classList.remove("highlight")
  }

  if(window.scrollY > 2050)
  {
    contact.classList.add("highlight")
    skills.classList.remove("highlight")
  }
  else{
    contact.classList.remove("highlight")
  }
}

window.addEventListener("scroll", highlight);

This works fine on my 24" monitor, but gets inaccurate if viewport height gets bigger, such as on a 27" monitor.

What better way can I target each page section with scroll?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Make a script where you define the elements that you need to reach in order for the state to update (with the use of .offsetTop)

Now the pixels value will dynamically change as the viewport changes.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda